package com.atguigu.gmall.seckill.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.seckill.pojo.UserRecode;
import com.atguigu.gmall.seckill.service.SeckillOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/17 22:47 星期一
 * description: 监听秒杀排队的消息完成秒杀异步下单
 */
@Component
@Log4j2
public class SeckillOrderAddListener {

    @Resource
    private SeckillOrderService seckillOrderService;

    /**
     * 秒杀异步下单: 真实下单
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "seckill_order_queue")
    public void seckillOrderAdd(Channel channel, Message message){
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //获取排队信息
        String s = new String(message.getBody());
        try{
            //秒杀下单
            seckillOrderService.realSeckillOrderAdd(JSONObject.parseObject(s, UserRecode.class));
            //确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                //拒绝过保存到日志,消息拒绝消费并丢弃
                log.error("秒杀下单失败,原因为:" + e.getMessage());
                log.error("秒杀下单失败,失败的信息为:" + s);
                channel.basicReject(deliveryTag,false);
            }catch (Exception e1){
                log.error("秒杀下单拒绝消息失败,原因为:" + e.getMessage());
                log.error("秒杀下单拒绝消息失败,失败的信息为:" + s);
            }
        }
    }
}
